package com.zh.zhbootauth.controller;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.zh.zhbootauth.service.UserClient;
import com.zh.zhbootcommon.domain.DResult;
import com.zh.zhbootcommon.entity.user.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;


/**
 * 描述: 用户登录、注册、注销
 *
 * @author: yanglin
 * @Date: 2021-03-05-9:54
 * @Version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/access/auth/")
public class LoginController {

    @Autowired
    UserClient userClient;

    @ApiOperation(value = "用户登录")
    @GetMapping("/login")
    public DResult<User> queryUserList(@RequestParam String account, @RequestParam String password){
        // 验证账户密码 判空
        assert (account == null || password == null) : "账户密码不能为空！";


        return DResult.of(null);
    }

    @GetMapping("/me")
    public DResult getCurrentUser(Authentication user, HttpServletRequest request) throws UnsupportedEncodingException {

        String s = user.getPrincipal().toString();
        String name = user.getName();
        String header = request.getHeader("Authorization");
        String token = StringUtils.substringAfter(header,"bearer ");
        Claims body = Jwts.parser().setSigningKey("internet_plus".getBytes("UTF-8"))
                .parseClaimsJws(token).getBody();

        String username = (String) body.get("username");
        log.info("解析token获取到的username为{}", username);
        log.info("从Authentication里获取到的username为{}", s);
        log.info("从Authentication里获取到的username为{}", name);
        return DResult.of(username);
    }
}
